package manager;


import interfaz.ManagerUserIf;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;

import type.EstadoType;
import domain.User;
import dto.UserDTO;
import exceptions.ExceptionUser;


@Stateless
public class ManagerUser implements ManagerUserIf{
	@SuppressWarnings("unused")
	private static Logger logger = Logger.getLogger(ManagerUser.class);
	@PersistenceContext(unitName="tpoai")
    EntityManager em;


	public ManagerUser() throws RemoteException {
		super();
		// TODO Auto-generated constructor stub
	}



	
	


	public UserDTO authenticate(String u, String p) throws ExceptionUser {
		@SuppressWarnings("rawtypes")
		Iterator q = em.createQuery("select c from User c where c.password=:pass AND c.username=:user").setParameter("pass", p).setParameter("user", u).getResultList().iterator();
		
		User c = null;
		  while(q.hasNext())  {
		    c = (User)q.next();
		    break;
		  }
		  if(c!=null)
			  if(c.getEstado().equals(EstadoType.ACTIVO))
				  return c.getVista();
		 
		  return null;
		  
	}







	@Override
	public void cambioestado(String id) {
		User a=em.find(User.class, Integer.parseInt(id));
		System.out.println(a.getEstado()+" LO ENCONTRO!");
		if(a.getEstado().equals(EstadoType.ACTIVO)){
			a.setEstado(EstadoType.NO_ACTIVO);
		}else if(a.getEstado().equals(EstadoType.NO_ACTIVO)){
			a.setEstado(EstadoType.ACTIVO);
		}
		
		em.persist(a);
	}







	@Override
	public List<UserDTO> getUsers() throws ExceptionUser, RemoteException {
		@SuppressWarnings("rawtypes")
		Iterator q = em.createQuery("select c from User c").getResultList().iterator();
		
		List<UserDTO> usuarios=new ArrayList<UserDTO>();
		
		  while(q.hasNext())
		  {
		    User c = (User)q.next();
		   // System.out.println("Se encontro usuario con " + c.getUsername());
		    usuarios.add(c.getVista());
		  }
		  return usuarios;
	}







	@Override
	public void save(UserDTO o) throws ExceptionUser, RemoteException {
		User u=new User();
		u.setEstado(o.getEstado());
		u.setPassword(o.getPassword());
		u.setUsername(o.getUsername());
		em.persist(u);
		em.flush();
		
		
	}

	

}
